<?php

namespace app\models\db;

use Yii;

/**
 * This is the model class for table "{{%category}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $parentId
 * @property string $type
 * @property integer $weight
 * @property integer $userId
 * @property string $description
 * @property string $addTime
 *
 * @property Article[] $articles
 * @property Article[] $activeArticles
 *
 */
class Category extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%category}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['parentId', 'weight', 'userId'], 'integer'],
            [['description'], 'string'],
            [['name', 'type'], 'string', 'max' => 64],
            [['addTime'], 'string', 'max' => 45],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '笔记id',
            'name' => '类型',
            'parentId' => '父级分类',
            'type' => '类型,book,course等',
            'weight' => '排序',
            'userId' => '创建者',
            'description' => '描述',
            'addTime' => '添加日期',
        ];
    }

    /**
     * 获取栏目包含的所有文章
     * @return \yii\db\ActiveQuery
     */
    public function getArticles()
    {
        return $this->hasMany(Article::className(),['categoryId'=>'id'])->inverseOf('category');
    }

    /**
     * 获取栏目包含的有效文章
     * @return \yii\db\ActiveQuery
     */
    public function getActiveArticles()
    {
        return $this->getArticles()->andWhere(['status'=>Article::STATUS_PUBLISHED]);
    }

    public function getParent()
    {
        return $this->hasOne(static::className(),['id'=>'parentId']);
    }

    public function getSubCategories()
    {
        return $this->hasMany(self::className(),['parentId'=>'id']);
    }
}
